package zhenniu.best.webview.zhenniuwebview.network;


import com.google.gson.JsonParser;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by admin on 2016/3/18.
 *
 */
public class Retrofit_RequestUtils {
    private volatile static Network.ApiService request;

    private Retrofit_RequestUtils(){}

    public static Network.ApiService getRequest(String url) {
        if (request == null) {
//            File   cacheFile = new File(BaseApplication.getContext().getExternalCacheDir(), "ssqsCache");
//            Cache  cache = new Cache(cacheFile, 1024 * 1024 * 50);
            synchronized (Retrofit_RequestUtils.class){
                if (request==null){
                    OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                    .cache(cache)
                            .connectTimeout((long) 2, TimeUnit.SECONDS)   //连接超过1.5秒就不进行网络请求
                            .readTimeout(20,TimeUnit.SECONDS)
                            .build();
                    request = new Retrofit.Builder()
                            .baseUrl(url)
                            .addConverterFactory(new NullOnEmptyConverterFactory())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(okHttpClient)
                            .build().create(Network.ApiService.class);
                }
            }


        }

        return request;
    }

    /**
     * 当返回空数据时
     * 服务端人员并不是返回理论意义上的空，null或者[]（数据集合空），而是返回没有响应体body，只有响应头header，content-length为0的Response
     * 会导致报错：android retrofit End of input at line 1 column 1 path
     */
    public static class NullOnEmptyConverterFactory extends Converter.Factory {

        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
            return new Converter<ResponseBody,Object>() {
                @Override
                public Object convert(ResponseBody body) throws IOException {

                    if (body.contentLength() == 0) {
                        return new JsonParser().parse("{\"result\":\"null\"}").getAsJsonObject();
                    }
                    return delegate.convert(body);
                }
            };
        }
    }

}
